package auth

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/go-redis/redis/v8"

	"github.com/go-basic/uuid"
	"log"
	"meituan/apps/admin/models"
	db2 "meituan/db"
	"meituan/utils/password"
	"strings"
	"time"
)

// AuthInfo 用户信息
type AuthInfo interface {
	SaveDB(expire int)
	GetToken() string
}

// DefaultAuthInfo 默认用户信息
type DefaultAuthInfo struct {
	Username      string
	IdentifyToken string
	Permissions   []string
	Resources     []string
	Roles         []string
}

func (info DefaultAuthInfo) GetToken() string {
	return info.IdentifyToken
}

// SaveDB 保存用户信息到Redis
func (info DefaultAuthInfo) SaveDB(expire int) {
	conn := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	defer conn.Close()
	marshal, _ := json.Marshal(info)
	e := conn.Set(
		context.Background(),
		fmt.Sprintf("%s:%s", info.Username, info.IdentifyToken),
		marshal,
		time.Hour*24,
	).Err()

	if e != nil {
		log.Println(e)
	}

}

// Realm 验证器
type Realm interface {
	HasPermission(info AuthInfo) (err error)
	HasResource(info AuthInfo) (err error)
	HasRole(info AuthInfo) (err error)
	AuthenticationInfo(user *models.Users) (info AuthInfo, err error)
}

// DefaultRealm 默认验证器
type DefaultRealm struct{}

// HasPermission 是否拥有权限
func (d DefaultRealm) HasPermission(info AuthInfo) (err error) {
	//defaultInfo := info.(DefaultAuthInfo)
	panic("implement me")
}

// HasResource 是否拥有资源
func (d DefaultRealm) HasResource(info AuthInfo) (err error) {
	//defaultInfo := info.(DefaultAuthInfo)
	panic("implement me")
}

// HasRole 是否拥有角色
func (d DefaultRealm) HasRole(info AuthInfo) (err error) {
	//defaultInfo := info.(DefaultAuthInfo)
	panic("implement me")
}

func (d DefaultRealm) AuthenticationInfo(user *models.Users) (info AuthInfo, err error) {
	db, _ := db2.NewDB()
	defer db.Close()
	dbUser := new(models.Users)
	db.Model(dbUser).First(dbUser, &models.Users{Username: user.Username})
	if dbUser.ID == 0 {
		err = errors.New("用户名或密码错误")
		return
	}

	if password.Verify(user.Password, dbUser.Password) {
		token, _ := uuid.GenerateUUID()
		token = strings.Replace(token, "-", "", -1)
		info = DefaultAuthInfo{
			Username:      user.Username,
			IdentifyToken: token,
			Permissions:   nil,
			Resources:     nil,
			Roles:         nil,
		}
	} else {
		err = errors.New("用户名或密码错误")
	}

	return
}
